package com.springboot.cloud.sysadmin.organization.rest;

import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.util.TreeNodeForVueUtile;
import com.springboot.cloud.common.core.utils.StringUtils;
import com.springboot.cloud.sysadmin.organization.entity.form.ResourceForm;
import com.springboot.cloud.sysadmin.organization.entity.form.ResourceQueryForm;
import com.springboot.cloud.sysadmin.organization.entity.param.ResourceQueryParam;
import com.springboot.cloud.sysadmin.organization.entity.po.Resource;
import com.springboot.cloud.sysadmin.organization.service.IResourceService;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
@RestController
@RequestMapping("/resource")
@Api(tags = "资源")
@Slf4j

public class ResourceController {

    @Autowired
    private   IResourceService resourceService;

    @ApiOperation(value = "新增资源", notes = "新增一个资源")
    @ApiImplicitParam(name = "resourceForm", value = "新增资源form表单", required = true, dataType = "ResourceForm")
    @PostMapping
    public Result add(@Valid @RequestBody ResourceForm resourceForm) {
        log.debug("resourceForm:{}", resourceForm);
        Resource resource = resourceForm.toPo(Resource.class);
        if (resourceService.add(resource)) {
            return Result.success("添加资源成功");
        } else {
            return Result.error("已存在相同名称的资源（或已经删除）");
        }
    }

    @ApiOperation(value = "删除资源", notes = "根据url的id来指定删除对象")
    @DeleteMapping
    public Result delete(@Valid @RequestBody Set<String> ids) {
        if (StringUtils.isEmpty(ids)) {
            return Result.error("没选中要删除的资源");
        } else if (resourceService.delete(ids)) {
            return Result.success("删除资源成功");
        }
        return Result.error("没选中要删除的用户");
    }


    @ApiOperation(value = "修改资源", notes = "修改指定资源信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "资源ID", required = true, dataType = "string"),
            @ApiImplicitParam(name = "resourceForm", value = "资源实体", required = true, dataType = "ResourceForm")
    })
    @PutMapping(value = "/{id}")
    public Result update(@PathVariable String id, @Valid @RequestBody ResourceForm resourceForm) {
        if (StrUtil.isBlank(id)) {
            return Result.error("id不可为空");
        }
        Resource resource = resourceForm.toPo(id, Resource.class);
        resource.setId(id);
        Boolean flag = resourceService.update(resource);
        if (flag) {
            return Result.success("修改资源成功");
        }
        return Result.error("更新失败,可能是字段重复导致！");
    }

    @ApiOperation(value = "获取资源", notes = "获取指定资源信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "资源ID", required = true, dataType = "string")
    @GetMapping(value = "/{id}")
    public Result get(@PathVariable String id) {
        if (StrUtil.isBlank(id)) {
            log.debug("get with id:{}", id);
            return Result.error("资源的id不可为空");
        }
        if (resourceService.getResource(id)) {
            return Result.success(resourceService.get(id));
        }
        return Result.error("查找不到对应值");
    }

    @ApiOperation(value = "查询资源", notes = "根据userId查询用户所拥有的资源信息")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户id", required = true, dataType = "string")
    @ApiResponses(
            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
    )
    @GetMapping(value = "/user/{username}")
    public Result queryByUsername(@PathVariable String username) {
        if (StrUtil.isBlank(username)) {
            return Result.error("账号不可为空值");
        }
        log.debug("query with username:{}", username);
        return Result.success(resourceService.query(username));
    }

    @ApiOperation(value = "查询所有资源", notes = "查询所有资源信息")
    @ApiResponses(
            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
    )
    @GetMapping(value = "/all")
    public Result queryAll() {
        List<Resource> resources = resourceService.getAll();
        return Result.success(resourceService.getAll());
    }

    @GetMapping(value = "/listResource")
    public Result listResource() {
        List<Resource> list = new ArrayList<>();
        list = resourceService.getAll();
        List<TreeNodeForVueUtile> tree = new ArrayList<>();
        for (Resource e : list) {
            tree.add(new TreeNodeForVueUtile(e.getName(), e.getId(), e.getParentId()));
        }
        List<TreeNodeForVueUtile> result = TreeNodeForVueUtile.getTreeResult(tree);
        return Result.success(result);
    }

    @ApiOperation(value = "搜索资源", notes = "根据条件搜索资源信息")
    @ApiImplicitParam(name = "resourceQueryForm", value = "资源查询参数", required = true, dataType = "RoleQueryForm")
    @ApiResponses(
            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
    )
    @PostMapping(value = "/conditions")
    public Result query(@Valid @RequestBody ResourceQueryForm resourceQueryForm) {
        if (resourceQueryForm.getCreatedTime() != null && !resourceQueryForm.getCreatedTime().isEmpty()) {
            resourceQueryForm.setCreatedTimeStart(resourceQueryForm.getCreatedTime().get(0));
            resourceQueryForm.setCreatedTimeEnd(resourceQueryForm.getCreatedTime().get(1));
        }
        List<Resource> list = new ArrayList<>();
        list = resourceService.query(resourceQueryForm.toParam(ResourceQueryParam.class));
        List<TreeNodeForVueUtile> tree = new ArrayList<>();
        for (Resource e : list) {
            tree.add(new TreeNodeForVueUtile(e, e.getName(), e.getId(), e.getParentId()));
        }
        List<TreeNodeForVueUtile> result = TreeNodeForVueUtile.getTreeResult(tree);
        return Result.success(result);
    }

    @ApiOperation(value = "搜索资源", notes = "根据条件搜索资源信息")
    @ApiImplicitParam(name = "resourceQueryForm", value = "资源查询参数", required = true, dataType = "RoleQueryForm")
    @ApiResponses(
            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
    )
    @PostMapping(value = "/searchResource")
    public Result searchResource(@Valid @RequestBody ResourceQueryForm resourceQueryForm) {
        if (resourceQueryForm.getCreatedTime() != null && !resourceQueryForm.getCreatedTime().isEmpty()) {
            resourceQueryForm.setCreatedTimeStart(resourceQueryForm.getCreatedTime().get(0));
            resourceQueryForm.setCreatedTimeEnd(resourceQueryForm.getCreatedTime().get(1));
        }
        return Result.success(resourceService.query(resourceQueryForm.toParam(ResourceQueryParam.class)));
    }

    @ApiOperation(value = "根据父id查询资源组", notes = "根据父id查询资源列表")
    @ApiImplicitParam(paramType = "path", name = "id", value = "资源父ID", required = true, dataType = "string")
    @GetMapping(value = "/parent/{id}")
    public Result search(@PathVariable String id) {
        if (StrUtil.isBlank(id)) {
            return Result.error("没有资源的父id");
        }
        log.debug("query with parent id:{}", id);
        return Result.success(resourceService.queryByParentId(id));
    }

}
